// pages/live-demonstration/liveDemonstration.js
const app = getApp()
let loadProgrammeMoreLock = false
let loadMoreLock = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabList:[{name: '我的方案', active:true, type: 'programme'}, {name: '素材库', active:false, type: 'material'}],
    materialType:[],
    presentationClassId: '1',
    selectedModule: 'programme',
    modalShow: false,
    CDNPATH:app.globalData.CDNPATH,
    navBarHeight: app.globalData.navBarHeight,
    statusBarHeight: app.globalData.statusBarHeight,
    isLoadMore: false,
    isNotdate: true,
    isProgrammeLoadMore: false,
    isProgrammeNotdate: false,
    endStatus: false,
    hastip: true,
    addProgrammShow: false,
    watchProgrammShow: false,
    programmeOneShow: false,
    programmeTwoShow: false,
    programmeThreeShow: false,
    programmeFourShow: false,
    fixedToMaterial: true,
    page: {
      currentPage: 1,
      pageSize: 10,
      total: 0,
    },
    pageProgramme: {
      currentPage: 1,
      pageSize: 10,
      total: 0,
    },
    customerId: '',
    productId: '',
    userName: '',
    programmeList: [],
    recommendList: [],
    presentationList: [],
    allSelectList: [],
  },
  swipeCheckX:0, //激活检测滑动的阈值
  swipeCheckState:0, //0未激活 1激活
  maxMoveLeft:74, //消息列表项最大左滑距离
  correctMoveLeft:74, //显示菜单时的左滑距离
  thresholdMoveLeft: 55,//左滑阈值，超过则显示菜单
  lastShowMsgId:'', //记录上次显示菜单的消息id
  moveX:0,  //记录平移距离
  showState:0, //0 未显示菜单 1显示菜单
  touchStartState:0, // 开始触摸时的状态 0 未显示菜单 1 显示菜单
  swipeDirection:0, //是否触发水平滑动 0:未触发 1:触发水平滑动 2:触发垂直滑动

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '现场演示'
    })
    console.log('进入现场演示',options)
    // if (options.customerId) {
    //   this.setData({
    //     customerId: options.customerId,
    //     productId: options.productId,
    //     userName: options.userName
    //   })
    //   this.getHasExist()
    //   this.addStage()
    // }
    const { callback } = options
    this.setData({
      navBarHeight: app.globalData.navBarHeight,
      statusBarHeight: app.globalData.statusBarHeight
    })
    // this.getProgrammeList()
    this.getMaterialClassList()
    this.getPresentationList()
    if (callback) {
      return false
    }
    this.getPresentationRecommendRuleCustomer()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      'page.currentPage': 1,
      'pageProgramme.currentPage': 1
    })
    this.getProgrammeList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  reback () {
    wx.navigateBack({delta: 1})
  },
  addStage () {
    const { customerId, productId } = this.data
    app.api.post({
      url: 'customer_stage_add',
      data: {
        customerId,
        productId,
        stage: 'show' // 演示阶段
      }
    })
  },
  getMarkFirstScheme () {
    app.api.get({
      url: 'cpic_user_markFirstScheme',
      data: {}
    }).then(res => {
      app.globalData.userInfo.firstScheme = 1
      wx.setStorageSync("userInfo", JSON.stringify(app.globalData.userInfo))
      console.log(res)
    })
  },
  getMarkFirstViewScheme () {
    app.api.get({
      url: 'cpic_user_markFirstViewScheme',
      data: {}
    }).then(res => {
      app.globalData.userInfo.firstViewScheme = 1
      wx.setStorageSync("userInfo", JSON.stringify(app.globalData.userInfo))
      console.log(res)
    })
  },
  closeGuide (e) {
    let index = e.currentTarget.dataset.type
    console.log(e)
    switch (index) {
      case 'add':
        if (!app.globalData.userInfo.firstViewScheme) {
          this.setData({
            addProgrammShow: false,
            watchProgrammShow: true
          })
        } else {
          this.setData({
            addProgrammShow: false
          })
        }
        break;
      case 'watch':
        this.setData({
          watchProgrammShow: false
        })
        this.getMarkFirstViewScheme()
        break;
      case 'one':
        this.setData({
          programmeOneShow: false,
          programmeTwoShow: true
        })
        break;
      case 'two':
        this.setData({
          programmeTwoShow: false,
          programmeThreeShow: true
        })
        break;
      case 'three':
        this.setData({
          programmeThreeShow: false,
          programmeFourShow: true
        })
        break;
      case 'four':
        this.setData({
          programmeFourShow: false
        })
        break;
      default:
        break;
    }
  },
  createProgramme () {
    this.setData({
      fixedToMaterial: true
    })
    let code = this.data.productId ? '03-00' : '03-01'
    wx.navigateTo({
      url: `/pages/programme/create-programme/createProgramme?productId=${this.data.productId}&sensors_ext=${code}&customerId=${this.data.customerId}&type=add`
    })
  },
  addProgramme () {
    console.log(this.data.allSelectList)
    var allSelectList = encodeURIComponent(JSON.stringify(this.data.allSelectList))
    let code = this.data.productId ? '03-00' : '03-01'
    if (this.data.allSelectList.length > 0) {
      wx.navigateTo({
        url: `/pages/programme/create-programme/createProgramme?sensors_ext=${code}&allSelectList=${allSelectList}&customerId=${this.data.customerId}&productId=${this.data.productId}&type=add&callback=my`
      })
    } else {
      wx.showToast({
        title: '请选择演示素材',
        icon: 'none',
        duration: 2000
      })
    }
  },
  goToDetail (e) {
    console.log(e)
    wx.navigateTo({
      url: `/pages/programme/watch-programme/watchProgramme?id=${e.currentTarget.dataset.item.id}`
    })
  },
  getHasExist () {
    app.api.post({
      url: 'scheme_exist',
      data: {customerId: this.data.customerId}
    }).then(res => {
      this.setData({
        modalShow: !res.exist
      })
      if (!res.exist) {
        this.getPresentationRecommendRuleCustomer()
      }
    })
  },
  getPresentationRecommendRuleCustomer () {
    app.api.post({
      url: 'presentation_page',
      data: {isRecommend: 'yes',currentPage:1,pageSize: 200 }
    }).then(res => {
      let arr = res.list || []
      if (arr.length>0) {
        arr.forEach((v) => {
          v.active = true
        })
      }
      this.setData({
        recommendList: arr || []
      })
      if (res.list.length > 0) {
        this.setData({
          modalShow: true
        })
      } else {
        this.setData({
          modalShow: false
        })
        // if (this.data.selectedModule === 'material') {
        //   this.setData({
        //     programmeOneShow: !app.globalData.userInfo.firstMaterial
        //   })
        //   if (!app.globalData.userInfo.firstMaterial) {
        //     this.getMarkFirstMaterial()
        //   }
        // }
      }
      console.log(res)
    })
  },
  // 切换到训练
  toggleTrain () {
    const { customerId, productId } = this.data
    wx.navigateTo({
      url: `/pages/home-page/train/train?customerId=${customerId}&productId=${productId}`
    })
  },
  // 方案的去演示
  programmeDemonstration (e) {
    const { id,presentationDetailResps} = e.currentTarget.dataset.item
    let presentationIds = []
    presentationDetailResps.forEach((v) => {
        presentationIds.push(v.id)
    })
    wx.navigateTo({
      url: `/pages/home-page/to-demonstration/toDemonstration?presentationIds=${presentationIds}&productId=${id}&type=demonstration`
    })
  },
  // 其他的去演示
  startDemonstration () {
    console.log(this.data.allSelectList)
    let presentationIds = []
    let code = this.data.productId ? '03-00' : '03-01'
    this.data.allSelectList.forEach((v) => {
      if (v.id && v.active) {
        presentationIds.push(v.id)
      }
    })
    if (this.data.allSelectList.length > 0) {
      if (this.data.allSelectList.length === 1) {
        if (this.data.allSelectList[0].materialType === 'link') {
          let param = { save: false, presentationIds: presentationIds, userName: this.data.userName, productId: this.data.productId, customerId: this.data.customerId }
          app.api.post({
            url: 'material_presentation_start',
            data: param
          }).then(res => {
            console.log(res)
            wx.navigateTo({ url: `/pages/home-page/watch-project/watchProject?sensors_ext=${code}&url=${encodeURIComponent(res[0].fileResourceUrl)}` })
          })
        } else {
          wx.navigateTo({
            url: `/pages/home-page/to-demonstration/toDemonstration?from=material&type=demonstration&presentationIds=${presentationIds}&save=false`
          }) 
        }
      } else {
        wx.navigateTo({
          url: `/pages/home-page/to-demonstration/toDemonstration?from=material&type=demonstration&presentationIds=${presentationIds}&save=false`
        })
      }
    } else {
      wx.showToast({
        title: '请选择演示素材',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 推荐的去演示
  toDemonstration () {
    let presentationIds = []
    this.data.recommendList.forEach((v) => {
      if (v.id && v.active) {
        presentationIds.push(v.id)
      }
    })
    if (presentationIds.length > 0) {
      this.setData({
        modalShow: false
      })
      if (presentationIds.length === 1) {
        if (this.data.recommendList[0].materialType === 'link') {
          let param = { save: false, presentationIds: presentationIds, userName: this.data.userName, productId: this.data.productId, customerId: this.data.customerId }
          app.api.post({
            url: 'material_presentation_start',
            data: param
          }).then(res => {
            console.log(res)
            wx.navigateTo({ url: `/pages/home-page/watch-project/watchProject?&url=${encodeURIComponent(res[0].fileResourceUrl)}` })
          })
        } else {
          wx.navigateTo({
            url: `/pages/home-page/to-demonstration/toDemonstration?from=material&type=demonstration&presentationIds=${presentationIds}&save=false`
          }) 
        }
      } else {
        wx.navigateTo({
          url: `/pages/home-page/to-demonstration/toDemonstration?from=material&type=demonstration&presentationIds=${presentationIds}&save=false`
        })
      }
    } else {
      wx.showToast({
        title: '请选择演示素材',
        icon: 'none',
        duration: 2000
      })
    }
  },
  close () {
    this.data.modalShow = !this.data.modalShow
    this.setData({
      modalShow: this.data.modalShow
    })
  },
  closeTip () {
    this.setData({
      hastip: false
    })
  },
  startProgramme (e) {
    let presentationIds = [e.currentTarget.dataset.item.id]
    if (e.currentTarget.dataset.item.materialType === 'link') {
      let params = {
        save: false,
        presentationIds: presentationIds,
        customerId: this.data.customerId
      }
      app.api.post({
        url: 'material_presentation_start',
        data: params
      }).then(res => {
        var arr = res
        wx.navigateTo({ url: `/pages/home-page/watch-project/watchProject?sensors_ext=${code}&url=${encodeURIComponent(arr[0].fileResourceUrl)}`})
      })
    } else {
      wx.navigateTo({
        url: `/pages/home-page/to-demonstration/toDemonstration?from=material&type=demonstration&presentationIds=${presentationIds}&save=false`
      }) 
    }
  },
  programmeToggle (e) {
    console.log(e)
    let { id } = e.currentTarget.dataset.item
    this.data.presentationList.forEach((v, k) => {
      if (id === v.id) {
        if (v.active) {
          console.log(1, v, this.data.allSelectList)
          v.active = false
          if (this.data.allSelectList.length > 0) {
            this.data.allSelectList.forEach((j, g) => {
              console.log(v, j)
              if (v.materialName === j.materialName) {
                this.data.allSelectList.splice(g, 1)
              }
            })
          }
        } else {
          v.active = true
          this.data.allSelectList.push(v)
        }
      }
    })
    console.log(this.data.allSelectList)
    this.setData({
      presentationList: this.data.presentationList,
      allSelectList: this.data.allSelectList
    })
  },
  toggle (e) {
    console.log(e)
    let name = e.currentTarget.dataset.name
    let type = e.currentTarget.dataset.type
    this.data.tabList.forEach((v, k) => {
      v.active = name === v.name
    })
    this.setData({
      tabList: this.data.tabList,
      selectedModule: type
    })
    if (type === 'programme') {
      // this.setData({
      //   fixedToMaterial: false,
      //   addProgrammShow: !app.globalData.userInfo.firstScheme
      // })
      // this.getMarkFirstScheme()
    }
    if (type === 'material') {
      this.getMaterialClassList()
      // this.setData({
      //   programmeOneShow: !app.globalData.userInfo.firstMaterial
      // })
      // if (!app.globalData.userInfo.firstMaterial) {
      //   this.getMarkFirstMaterial()
      // }
    }
    
  },
  getMarkFirstMaterial () {
    app.api.get({
      url: 'cpic_user_markFirstMaterial',
      data: {}
    }).then(res => {
      app.globalData.userInfo.firstMaterial = 1
      wx.setStorageSync("userInfo", JSON.stringify(app.globalData.userInfo))
      console.log(res)
    })
  },
  recommendToggle (e) {
    let { id } = e.currentTarget.dataset.item
    this.data.recommendList.forEach((v, k) => {
      if (id === v.id) {
        if (v.active) {
          v.active = false
        } else {
          v.active = true
        }
      }
    })
    this.setData({
      recommendList: this.data.recommendList
    })
  },
  getMaterialClassList () {
    app.api.post({
      url: 'presentationClass_list',
      data: {}
    }).then(res => {
      let arr = res || []
      arr.unshift({id: '1',presentationClassName: '全部'})
      arr.push({id: '0',presentationClassName: '其他'})
      this.setData({
        materialType: arr
      })
      console.log(res)
    })
  },
  toggleType (e) {
    let { id } = e.currentTarget.dataset
    this.setData({
      presentationClassId: id,
      'pageProgramme.currentPage': 1
    })
    this.getPresentationList()
  },
  loadMore () {
    console.log('加载了更多')
    const { page, programmeList } = this.data
    if (loadMoreLock ===false &&  page.total > programmeList.length) {
      loadMoreLock = true;
      this.setData({
        'page.currentPage': page.currentPage + 1,
        'isLoadMore': true
      })
      this.getProgrammeList()
    }
  },
  loadProgrammeMore () {
    console.log('加载了更多')
    const { pageProgramme, presentationList } = this.data
    if (loadProgrammeMoreLock ==false && pageProgramme.total > presentationList.length) {
      loadProgrammeMoreLock = true;
      this.setData({
        'pageProgramme.currentPage': pageProgramme.currentPage + 1,
        'isProgrammeLoadMore': true
      })
      this.getPresentationList()
    }
  },
  getProgrammeList: function () {
    let { page, programmeList } = this.data
    const params = {
      currentPage: page.currentPage,
      pageSize: page.pageSize,
    }
    app.api.post({
      url: 'recommend_plan_vx_presentation_list',
      data: params
    }).then(res => {
      let arr = []
      if (res.list.length > 0) {
        arr = res.list
        if (this.data.isLoadMore) {
          console.log('执行加载')
          programmeList.push(...arr)
        } else {
          console.log('执行加载2')
          programmeList = arr
        }
        this.setData({
          programmeList,
          isLoadMore: false,
          isNotdate: false,
          tabList: this.data.tabList,
          'page.total': Number(res.total)
        })
        // if (this.data.selectedModule === 'programme') {
        //   this.setData({
        //     addProgrammShow: !app.globalData.userInfo.firstScheme
        //   })
        //   this.getMarkFirstScheme()
        // }
      } else {
        if (this.data.fixedToMaterial) {
          // this.data.tabList[0].active = false
          // this.data.tabList[1].active = true
          // this.setData({
          //   selectedModule: 'material',
          // })
        }
        this.setData({
          programmeList: [],
          tabList: this.data.tabList,
          isNotdate: true
        })
        // if (this.data.selectedModule === 'material' && !this.data.customerId) {
        //   this.setData({
        //     programmeOneShow: !app.globalData.userInfo.firstMaterial
        //   })
        //   if (!app.globalData.userInfo.firstMaterial) {
        //     this.getMarkFirstMaterial()
        //   }
        // }
      }
      loadMoreLock = false
    }).catch(e=>{
      loadMoreLock = false
    })
    console.log(this.data.selectedModule)
  },
  getPresentationList () {
    let { pageProgramme, presentationList, presentationClassId } = this.data
    const params = {
      currentPage: pageProgramme.currentPage,
      pageSize: pageProgramme.pageSize,
      presentationClassId
    }
    app.api.post({
      url: 'presentation_page',
      data: params
    }).then(res => {
      let arr = []
      if (res.list.length > 0) {
        arr = res.list
        for (let i = 0; i < arr.length; i++) {
          for (let j = 0; j < this.data.allSelectList.length; j++) {
            if (this.data.allSelectList[j].materialName === arr[i].materialName) {
              arr[i].active = true
            }
          }
        }
        if (this.data.isProgrammeLoadMore) {
          console.log('执行加载')
          presentationList.push(...arr)
        } else {
          console.log('执行加载2')
          presentationList = arr
        }
        console.log(presentationList)
        this.setData({
          presentationList,
          isProgrammeLoadMore: false,
          isProgrammeNotdate: false,
          'pageProgramme.total': Number(res.total)
        })
      } else {
        this.setData({
          presentationList: [],
          isProgrammeNotdate: true
        })
      }
      loadProgrammeMoreLock = false;
    }).catch(e=>{
      console.log(e)
      loadProgrammeMoreLock = false;
    })
  },
  saveToProgramme () {
    let recommendList = []
    let code = this.data.productId ? '03-00' : '03-01'
    this.data.recommendList.forEach((v) => {
      if (v.active) {
        recommendList.push(v)
      }
    })
    var allSelectList = encodeURIComponent(JSON.stringify(recommendList))
    if (recommendList.length > 0) {
      this.setData({
        modalShow: false
      })
      wx.navigateTo({
        url: `/pages/programme/create-programme/createProgramme?sensors_ext=${code}&allSelectList=${allSelectList}&type=edit&customerId=${this.data.customerId}&userName=${this.data.userName}&productId=${this.data.productId}`
      })
    } else {
      wx.showToast({
        title: '请选择演示素材',
        icon: 'none',
        duration: 2000
      })
    }
  },
  ontouchstart: function(e) {
    console.log('开始')
    if (this.showState === 1) {
      this.touchStartState = 1;
      this.showState = 0;
      this.moveX = 0;
      this.translateXMsgItem(this.lastShowMsgId, 0, 200);
      this.lastShowMsgId = "";
      return;
    }
    this.firstTouchX = e.touches[0].clientX;
    this.firstTouchY = e.touches[0].clientY;
    if (this.firstTouchX > this.swipeCheckX) {
      this.swipeCheckState = 1;
    }
    this.lastMoveTime = e.timeStamp;
  },
  ontouchmove: function(e) {
    console.log('移动')
    if (this.swipeCheckState === 0) {
      return;
    }
    //当开始触摸时有菜单显示时，不处理滑动操作
    if (this.touchStartState === 1) {
      return;
    }
    var moveX = e.touches[0].clientX - this.firstTouchX;
    var moveY = e.touches[0].clientY - this.firstTouchY;
    //已触发垂直滑动，由scroll-view处理滑动操作
    if (this.swipeDirection === 2) {
      return;
    }
    //未触发滑动方向
    if (this.swipeDirection === 0) {
      console.log(Math.abs(moveY));
      //触发垂直操作
      if (Math.abs(moveY) > 4) {
        this.swipeDirection = 2;

        return;
      }
      //触发水平操作
      if (Math.abs(moveX) > 4) {
        this.swipeDirection = 1;
        this.setData({scrollY:false});
      }
      else {
        return;
      }
        
    }
    //禁用垂直滚动
    // if (this.data.scrollY) {
    //   this.setData({scrollY:false});
    // }

    this.lastMoveTime = e.timeStamp;
    //处理边界情况
    if (moveX > 0) {
      moveX = 0;
    }
    //检测最大左滑距离
    if (moveX < -this.maxMoveLeft) {
      moveX = -this.maxMoveLeft;
    }
    this.moveX = moveX;
    this.translateXMsgItem(e.currentTarget.id, moveX, 0);
  },
  ontouchend: function(e) {
    console.log('结束')
    this.swipeCheckState = 0;
    var swipeDirection = this.swipeDirection;
    this.swipeDirection = 0;
    if (this.touchStartState === 1) {
      console.log(1)
      this.touchStartState = 0;
      this.setData({scrollY:true, endStatus: false});
      return;
    } 
    //垂直滚动，忽略
    if (swipeDirection !== 1) {
      console.log(2)
      return;
    }
    if (this.moveX === 0) {
      console.log(3)
      this.showState = 0;
      //不显示菜单状态下,激活垂直滚动
      this.setData({scrollY:true});
      return;
    }
    if (this.moveX === this.correctMoveLeft) {
      console.log(4)
      this.showState = 1;
      this.lastShowMsgId = e.currentTarget.id;
      return;
    }  
    if (this.moveX < -this.thresholdMoveLeft) {
      console.log(5)
      this.moveX = -this.correctMoveLeft;
      this.showState = 1;
      this.lastShowMsgId = e.currentTarget.id;
    }
    else {
      console.log(6)
      this.moveX = 0;
      this.showState = 0;
      //不显示菜单,激活垂直滚动
      this.setData({scrollY:true});
    }
    this.translateXMsgItem(e.currentTarget.id, this.moveX, 500);
    this.setData({
      endStatus: true
    })
    console.log(7)
    //this.translateXMsgItem(e.currentTarget.id, 0, 0);
  },
  onDeleteMsgTap: function(e) {
    console.log(e)
    this.deleteMsgItem(e);
  },
  deleteMsgItem: function(e) {
    var animation = wx.createAnimation({duration:200});
    animation.height(0).opacity(0).step();
    this.animationMsgWrapItem(e.currentTarget.id, animation);
    var s = this;
    setTimeout(function() {
      var id = e.currentTarget.id
      console.log(id)
      app.api.post({
        url: 'recommend_plan_delete',
        data: {productId: id}
      }).then(res => {
        s.setData({
          page: {
            currentPage: 1,
            pageSize: 10,
            total: 0
          },
          programmeList: []
        })
        console.log(4)
        wx.showToast({
          icon: 'none',
          title: '删除成功',
        })
        s.getProgrammeList()
      })
      }, 200);
    this.showState = 0;
    this.setData({scrollY:true});
  },
  translateXMsgItem: function(id, x, duration) {
    var animation = wx.createAnimation({duration:duration});
    animation.translateX(x).step();
    this.animationMsgItem(id, animation);
  },
  animationMsgItem: function(id, animation) {
    var index = this.getItemIndex(id);
    var param = {};
    var indexString = 'programmeList[' + index + '].animation';
    param[indexString] = animation.export();
    this.setData(param);
  },
  animationMsgWrapItem: function(id, animation) {
    var index = this.getItemIndex(id);
    var param = {};
    var indexString = 'programmeList[' + index + '].wrapAnimation';
    param[indexString] = animation.export();
    this.setData(param);
  },
  getItemIndex: function(id) {
    var msgList = this.data.programmeList;
    console.log(msgList)
    for (var i = 0; i < msgList.length; i++) {
      if (msgList[i].id === id) {
        return i;
      }
    }
    return -1;
  }
})